package com.odm.communitymanage.ui.mine.MyComplaint

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.jeremyliao.liveeventbus.LiveEventBus
import com.odm.communitymanage.R
import com.odm.communitymanage.base.BaseFragment
import com.odm.communitymanage.base.BaseMVVMFragment
import com.odm.communitymanage.core.Constants
import com.odm.communitymanage.core.bean.MyComplaintData
import com.odm.communitymanage.core.bean.NetCallBack
import com.odm.communitymanage.core.bean.PostEvaluateRepair
import com.odm.communitymanage.core.net.ApiService
import com.odm.communitymanage.ui.ImageDetailActivity
import com.odm.communitymanage.util.GlideUtils
import com.odm.communitymanage.widget.PointProcessBar
import com.rxjava.rxlife.lifeOnMain
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_my_complaint_detail.*
import kotlinx.android.synthetic.main.fragment_my_submit_repair_detail.*
import rxhttp.wrapper.param.RxHttp

/**
 * @description: 我的投诉详情 页面
 * @author: ODM
 * @date: 2020/4/16
 */
class MyComplaintDetailFragment : BaseFragment() {

    /**
     * 评分条回调值变量
     */
    var evaluateValue : Float ?= 0f
    var eventId : Int ?= -1

    private var disposable : Disposable?= null


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        registerLiveEvent()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if(disposable?.isDisposed == false){
            disposable?.dispose()
        }
    }


    override fun initViews() {}

    /**
     * 加载 打分状态的布局
     * @param starValue Float  分值
     */
    private fun loadEvaluateStateLayout(starValue : Float){
        val viewStub : View = evaluateStatus_MyComplaintDetail.inflate()
        val evaluateLayout = viewStub.findViewById<View>(R.id.evaluateStatusInflate_MyComplaintDetail)
        val evaluateStatus = evaluateLayout.findViewById<RatingBar>(R.id.rbEvaluateStatus)
        evaluateStatus?.rating = starValue
    }

    /**
     * 加载出ViewStub的提交评价布局
     */
    private fun loadPostEvaluateLayout(){
        val viewStub : View = evaluate_MyComplaintDetail.inflate()
        val evaluateLayout = viewStub.findViewById<View>(R.id.evaluateInflate_MyComplaintDetail)
        val evaluateRatingBar = evaluateLayout.findViewById<RatingBar>(R.id.rbEvaluate)
        evaluateRatingBar?.onRatingBarChangeListener =
            RatingBar.OnRatingBarChangeListener { ratingBar, value, fromUser ->
                evaluateValue = value
            }
        val btnPostEvaluate : TextView = evaluateLayout.findViewById<TextView>(R.id.btnPostEvaluate)
        btnPostEvaluate.setOnClickListener {
            //提交 评价请求
            postEvaluate(btnPostEvaluate)
        }
    }

    /**
     * POST请求 提交评价
     * @param view TextView
     */
    private fun postEvaluate(view: TextView){
        //不允许打出 0 分的评价
        if(evaluateValue == 0f || eventId == -1){
            ToastUtils.showShort("请先做出评价")
            return
        }

        disposable = RxHttp.postJson(ApiService.EVALUATE_MY_COMPLAINT)
            .addAll(GsonUtils.toJson(PostEvaluateRepair(eventId ?: 0 , evaluateValue?.toInt() ?: 0)))
            .asClass(NetCallBack::class.java)
            .lifeOnMain(this)
            .subscribe({
                if(it.code == 1){
                    showSuccessSnack(getString(R.string.post_success))
                    view.text = "感谢您的反馈与评价，祝您生活愉快"
                }else {
                    ToastUtils.showShort(it.message)
                }
            } , {
                ToastUtils.showShort(it.message)
            })

    }


    private fun registerLiveEvent(){
        LiveEventBus.get(Constants.EVENT_MY_COMPLAINT_DETAIL , MyComplaintData::class.java)
            .observeSticky(this  ,
                Observer<MyComplaintData> {
                    it?.let {
                        loadMyComplaintData(it)
                    }
                    if(it == null){
                        ToastUtils.showShort(getString(R.string.network_mistake))
                    }
                })
    }


    /**
     * 加载 我的投诉的详情
     * @param data MyComplaintData?
     */
    private fun loadMyComplaintData(data : MyComplaintData ?){
        //根据当前事件的处理状态 --> 控件状态
        when(data?.status){
            1 -> {
                //处理中，改变 节点进度条的状态

            }
            2 -> {
                //0 颗星 说明尚未评价
                if(data.start > 0){
                    //已解决,若有评价，则显示评价条加载 星形评分指示器
                    loadEvaluateStateLayout(data.start.toFloat())
                }else{
                    //已解决但是还没去评价，显示 提交评价布局
                    loadPostEvaluateLayout()
                }
            }
            else -> {

            }
        }

        tvContent_MyComplaintDetail?.text = data?.content
        //根据匿名状态显示
        tvAnonymous_MyComplaintDetail.visibility = if(data?.anonymous == true){
            View.VISIBLE
        }else {
            View.GONE
        }
        data?.imgs?.let {
            //加载ImageView
            for (url in it) {
                var target: ImageView? = null
                if (ivPhoto_0_MyComplaintDetail.visibility == View.INVISIBLE) {
                    target = ivPhoto_0_MyComplaintDetail
                } else if (ivPhoto_1_MyComplaintDetail.visibility == View.INVISIBLE) {
                    target = ivPhoto_1_MyComplaintDetail
                }
                target?.apply {
                    visibility = View.VISIBLE
                    //加载图片
                    GlideUtils
                        .getInstance()
                        .loadImageUrl(requireContext(),url ,target)
                    //点击事件，跳转加载大图Activity
                    setOnClickListener {
                        LiveEventBus
                            .get(Constants.IMAGE_URL)
                            .post(url)
                        ActivityUtils.startActivity(ImageDetailActivity::class.java)
                    }
                }
            }
        }

        //获取 事件 ID
        eventId = data?.id?:-1
        val set : MutableSet<Int> = mutableSetOf<Int>()
        set.add(0)
        set.add(1)
        set.add(2)

        //配置节点进度条
        val indexSet:MutableSet<Int> = mutableSetOf()
        var i = 0
        while(i <= data?.status?:-1){
            indexSet.add(i)
            i++
        }
        pb_MyComplaintDetail.show(arrayListOf(
            getString(R.string.suspending),
            getString(R.string.processing),
            getString(R.string.processed)
        ) ,
            indexSet)


    }




    override fun getLayoutId(): Int {
        return R.layout.fragment_my_complaint_detail
    }


}